'use strict';

const Controller = require('egg').Controller;

class CheckController extends Controller {
    //获取
    async getCheck() {
        const { ctx } = this;
        const { state } = ctx.query;
        const data = await this.app.mysql.query(`SELECT * FROM checkes WHERE state Like "%${state}%" `);
        data.forEach((item, index) => {
            item.key = index + 1;
        })
        ctx.body = {
            code: 200,
            data,
        };
    }

    //搜索
    async searchCheck() {
        const { ctx } = this;
        const { province, city, county, word, state } = ctx.query;
        const data = await this.app.mysql.query(`SELECT * FROM checkes WHERE
        city Like "%${city}%"
        and province Like "%${province}%"
        and state Like "%${state}%"
        and county Like "%${county}%"
        and word Like "%${word}%"`);
        data.forEach((item, index) => {
            item.key = index + 1;
        })
        ctx.body = {
            code: 200,
            data,
        };
    }

    //编辑
    async editorCheck() {
        const { ctx } = this;
        const { arr } = ctx.request.body;
        let list = await this.app.mysql.get('checkes', { id: arr.id });
        list.name = arr.name
        list.area = arr.area
        list.price = arr.price
        list.content = arr.content
        list.title = arr.title
        list.province = arr.province
        list.city = arr.city
        list.county = arr.county
        list.word = arr.word
        const data = await this.app.mysql.update('checkes', {
            ...list
        });
        if (data.affectedRows !== 1) {
            ctx.body = {
                code: 500,
                message: "修改失败"
            };
        }
        ctx.body = {
            code: 200,
            message: "修改成功"
        };
    }
    //删除
    async deleteCheck() {
        const { ctx } = this;
        const { id } = ctx.query;
        const data = await this.app.mysql.delete('checkes', {
            id: id,
        });
        if (data.affectedRows !== 1) {
            ctx.body = {
                code: 500,
                message: "删除失败"
            };
        }
        ctx.body = {
            code: 200,
            message: "删除成功"
        };
    }

    //开关的编辑
    async stateCheck() {
        const { ctx } = this;
        const { id } = ctx.request.body;
        let list = await this.app.mysql.get('checkes', { id: id });
        list.state = !list.state;
        const data = await this.app.mysql.update('checkes', {
            ...list
        });
        if (data.affectedRows !== 1) {
            ctx.body = {
                code: 500,
                message: "修改失败"
            };
        }
        ctx.body = {
            code: 200,
            message: "修改成功"
        };
    }
}

module.exports = CheckController;
